﻿function initCanvas(dotnetHelper) {

    var canvas = document.getElementById('myCanvas');



    canvas.addEventListener('mousedown', function (e) {

        dotnetHelper.invokeMethodAsync('MouseDown', e.offsetX, e.offsetY);

        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        Line.clearSelection(); // 清除之前的选中状态
        lines.forEach(function (item, index) {
            item.isSelected = false;
        })
        for (let line of lines) {
            if (line.isPointOnLine(x, y)) {
                line.isSelected = true;
                Line.selectedLine = line; // 更新当前选中的线  
                drawLines(); // 重绘所有线以显示选中状态  
                break;
            }
        }
        dotnetHelper.invokeMethodAsync('MouseSelect', Line.selectedLine);
    });



    canvas.addEventListener('mousemove', function (e) {

        dotnetHelper.invokeMethodAsync('MouseMove', e.offsetX, e.offsetY);

    });



    canvas.addEventListener('mouseup', function (e) {

        dotnetHelper.invokeMethodAsync('MouseUp', e.offsetX, e.offsetY);

    });

}

function drawLine(x1, y1, x2, y2) {

    var canvas = document.getElementById('myCanvas');

    var ctx = canvas.getContext('2d');

    ctx.strokeStyle = 'green';

    ctx.beginPath();

    ctx.moveTo(x1, y1);

    ctx.lineTo(x2, y2);

    ctx.stroke();

}

function clearCanvas() {

    var canvas = document.getElementById('myCanvas');

    var ctx = canvas.getContext('2d');

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    lines = [];
}

function drawLines() {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    lines.forEach(line => line.draw());
}

// 添加线的函数  
function addLine(startX, startY, endX, endY) {
    var isExist = lines.filter(function (item) {
        return item.startX === startX && item.startY === startY && item.endX === endX && item.endY === endY;
    });
    if (isExist.length === 0) {
        Line.clearSelection(); // 清除之前的选中状态
        lines.forEach(function (item, index) {
            item.isSelected = false;
        })
        const newLine = new Line(startX, startY, endX, endY, true);
        lines.push(newLine);
        drawLines(); // 绘制所有线，包括新添加的  
    }
}

function getCanvas() {

    return document.getElementById('myCanvas').getContext('2d');

}

//删除线
function deleteLine(lineId) {
    lines = lines.filter(function (item) {
        return item.Id !== lineId;
    });
    drawLines(); // 重新绘制所有线
}

let lines = [];

function generateSecureUUID() {
    return crypto.randomUUID();
}

class Line {
    constructor(startX, startY, endX, endY, isSelected = false) {
        this.startX = startX;
        this.startY = startY;
        this.endX = endX;
        this.endY = endY;
        this.isSelected = isSelected;
        this.Id = generateSecureUUID();
    }



    draw() {

        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(this.startX, this.startY);
        ctx.lineTo(this.endX, this.endY);
        ctx.strokeStyle = this.isSelected ? 'red' : 'black';
        ctx.stroke();
    }

    isPointOnLine(x, y, tolerance = 2) { // 添加一个容忍度参数来允许在线附近点击  
        const A = { x: this.startX, y: this.startY };
        const B = { x: this.endX, y: this.endY };
        const C = { x, y };

        const AB_squared = Math.pow(B.x - A.x, 2) + Math.pow(B.y - A.y, 2);
        if (AB_squared === 0) return false; // 防止除零错误  

        const t = ((C.x - A.x) * (B.x - A.x) + (C.y - A.y) * (B.y - A.y)) / AB_squared;

        if (t < 0) return false; // 点C在AB的延长线上  
        if (t > 1) return false; // 点C在BA的延长线上  

        const projection = {
            x: A.x + t * (B.x - A.x),
            y: A.y + t * (B.y - A.y)
        };

        // 计算点C到线段AB的垂直距离  
        const distance = Math.sqrt(Math.pow(C.x - projection.x, 2) + Math.pow(C.y - projection.y, 2));

        // 如果距离小于容忍度，则认为点C在线段AB上  
        return distance <= tolerance;
    }

    static selectedLine = null;

    static clearSelection() {
        if (Line.selectedLine) {
            Line.selectedLine.isSelected = false;
            Line.selectedLine = null;
        }
    }

    toggleSelect() {
        this.isSelected = !this.isSelected;
    }
}